import { isClosed } from "../utils/handle";
import type { CallBack, PriorComposer, ReactiverLike } from "../types";
import Composer from "./composer";

export default class Prior extends Composer implements PriorComposer {
  private prior?: CallBack<any, CallBack>;

  constructor(reactiver: ReactiverLike) {
    super(reactiver);
  }

  set(val: CallBack, caller: any = this): void {
    this.prior = () => {
      return val.bind(caller);
    };
  }

  run() {
    if (isClosed(this.reactiver)) {
      return undefined;
    }
    try {
      
      let result = this.prior?.()();
      if (result === undefined && this.prior) {
        throw new Error("Prior must have a return!");
      }
      return result;
    } catch (err:any) {
      this.reactiver.closed = true;
      throw new Error(err.message || err);
  }
  }

  destroy(arg?: any): void {}
}
